package humanMirror.controller.actions;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;
import humanMirror.model.questionLibrary.SqlWorker;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginCheckAction implements Action {

	public String perform(HttpServletRequest request, HttpServletResponse response){

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		try{

			if (SqlWorker.checkRegistration(login,password)) {
				HttpSession session = request.getSession(true);
				session.setAttribute("user", login);
				session.setAttribute("controller", new Controller(new Human()));
				session.setAttribute("questionNumber", 0);
				return "/main.jsp";
			} else {
				return showErrorPage(request,"Invalid username/password.");
			}

		} catch (Exception e){
			request.setAttribute("errorMessage", e.toString());
			return showErrorPage(request, e.toString());
		}
		//return null;
	}//perform
   private String showErrorPage(HttpServletRequest request,String error){
       request.setAttribute("errorMessage", error);
       return "/error.jsp";
   }
}

